#include "mainwindow.h"
#include "ui_mainwindow.h"



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    QStringList Baud_List;
    Baud_List <<"4800" << "9600"<<"19200"<<"38400"<<"57600"<<"115200"<<"128000"<<"256000";
    m_serial =  new serial;

    ui->setupUi(this);

    Port_List = m_serial->scanSerial();         //获取可用串口
    //qDebug()<<"prot list:"<<Port_List;
    for(int i = 0;i<Port_List.size();i++)
    {
        ui->comboBox->addItem(Port_List[i]);
    }

    for(int i = 0;i<Baud_List.size();i++)
    {
        ui->comboBox_2->addItem(Baud_List[i]);

    }
    ui->comboBox_2->setEditable(true);      //允许添加编辑
    // 当下位机中有数据发送过来时就会响应这个槽函数
    connect(m_serial, SIGNAL(readSignal()), this, SLOT(readSerialData()));

    connect(ui->pushButton, SIGNAL(clicked()),this,SLOT(pBtn_onClicked()));
    connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(pBtn2_onClicked()));       //清空接收显示区
    connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(pBtn3_onClicked()));       //清空发送显示区
    connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(pBtn4_onClicked()));       //串口数据发送
    //connect(ui->comboBox,SIGNAL(clicked()),this,SLOT(timerEvent()));
    initTimer();
}

void MainWindow::pBtn_onClicked()
{
    QString serialName;
    QString baudRate;

    bool ret = false;
    if(openflag == true)                                    //关闭串口
    {
        ui->pushButton->setText("打开串口");
        qDebug() << "打开串口";
        openflag = false;
        m_serial->close();

        ui->comboBox->setEnabled(true);
        ui->comboBox_2->setEnabled(true);
    }
    else                                                     //开启串口
    {
        ui->pushButton->setText("关闭串口");
        qDebug() << "关闭串口";
        openflag = true;

        serialName = ui->comboBox->currentText();             //获取串口号
        baudRate = ui->comboBox_2->currentText();             //获取波特率
        qDebug()<<"serialName"<<serialName;
        qDebug()<<"BaudRate="<< baudRate;

        ret = m_serial->open(serialName,baudRate.toInt());
        if(ret == false)
        {
           qDebug()<<"串口打开失败";
        }
        else                                                //串口打开成功
        {
           qDebug()<<"串口打开成功";
           ui->comboBox->setEnabled(false);
           ui->comboBox_2->setEnabled(false);
        }
    }
    //qDebug()<<"BaudRate="<<ui->comboBox_2->currentText();     //获取当前文本
}

void MainWindow::pBtn2_onClicked()                              //清空接收显示区
{
    ui->textEdit->clear();
}

void MainWindow::pBtn3_onClicked()                              //清空发送显示区
{
    ui->textEdit_2->clear();
}


MainWindow::~MainWindow()
{
    delete ui;
    delete m_serial;
}

void MainWindow::initTimer()
{
    //if(nullptr == m_timer)
        m_timer = new QTimer;
    //设置定时器是否为单次触发。默认为 false 多次触发
    m_timer->setSingleShot(false);
    //启动或重启定时器, 并设置定时器时间：毫秒
    m_timer->start(1000);
    //定时器触发信号槽
    connect(m_timer, SIGNAL(timeout()), this, SLOT(m_timerEvent()));
}

void MainWindow::readSerialData()
{
#if 0
    QString originStr = ui->recvTextEdit->toPlainText(); // 保存接收文本框原本的数据
    ui->recvTextEdit->clear();
    ui->recvTextEdit->setText(originStr);
    ui->recvTextEdit->moveCursor(QTextCursor::End); // 在末尾移动光标一格
    ui->recvTextEdit->insertPlainText(m_serial->getReadBuf().toHex(' ')); // 插入新读取数据（中间以一格空格间隔）
    ui->recvTextEdit->moveCursor(QTextCursor::End); // 在末尾移动光标一格
    ui->recvTextEdit->insertPlainText(" ");

    m_serial->clearReadBuf(); // 读取完后，清空数据缓冲区
#endif
    QString serialBuf = m_serial->getReadBuf();         //接收串口数据
    //QTextCodec code;
    //QTextCodec* gb2312Codec;
#if 0       ///自动换行
    //ui->textEdit->clear();
    //ui->textEdit->append(serialBuf.toUtf8());
#endif
    ui->textEdit->insertPlainText(serialBuf.toUtf8());
    //ui->textEdit->setText(serialBuf.toLocal8Bit().data());
    qDebug()<<(m_serial->getReadBuf())<<endl;
    //m_serial->clearReadBuf();
}

void MainWindow::m_timerEvent()
{
    QStringList Port_List_now;
    bool Refresh_flag = false;
    if(m_timer->isActive())                         //判断定时器是否运行
        m_timer->stop();                            //停止定时器
    Port_List_now = m_serial->scanSerial();         //获取可用串口

    if(Port_List_now != Port_List)                  //判断是否需要刷新
    {
        Port_List = Port_List_now;
        qDebug()<<"refresh List"<<endl;
        Refresh_flag = true;
    }

    if(Refresh_flag == true)                        //更新
    {
        Refresh_flag = false;
        ui->comboBox->clear();
        for(int i = 0;i<Port_List_now.size();i++)
        {
             ui->comboBox->addItem(Port_List_now[i]);
        }
    }
    m_timer->start();
}

void MainWindow::pBtn4_onClicked()                  //发送数据
{
    QByteArray m_array("12345");
    if(openflag == true)
    {
        //发送16进制数据
       // QByteArray sendData = m_serial->hexStringToByteArray(ui->textEdit_2->toPlainText());
       //QString senddata = ui->textEdit_2->toPlainText();
       //QByteArray sendData =  ui->textEdit_2->toPlainText()
       //m_serial->sendData();
       QByteArray data = ui->textEdit_2->toPlainText().toUtf8();
       //data = "hello\nworld";
       qDebug() << data;
       m_serial->sendData(data);
    }

}


